<template>
	<view>
		<template v-if="userStore.isLogined">
			<teacher-index v-if="userStore.role === 'teacher'" />
			<student-index v-if="userStore.role === 'student'" />
		</template>
	</view>
</template>

<script>
	import { useUserStore } from '@/store'
  	import { http } from '@/utils/http'

	import studentIndex from '../student/student-index.vue'
	import teacherIndex from '../teacher/teacher-index.vue'
	

	export default {
		components: {
			studentIndex,
			teacherIndex
		},
		data() {
			return {
				userStore: useUserStore(),
				openid: null,
			}
		},
		created(){

		},
		onLoad(options) {
			this.openid = options.openid || null
		},
		onShow() {
			this.checkLogin()
		},
		methods: {
			checkLogin: function() {
				if (this.userStore.isLogined) { return }
				if (this.openid === null) {
					// 请求微信授权
					console.log('请求微信授权')
					const hostname = location.hostname
					if(hostname == 'edu.younice.top') {
						location.href = 'http://edu.younice.top/web/we-chat/login'
					} else {
						location.href = 'http://' + hostname +':8000/web/we-chat/login'
					}
					return
				}
			
				// 后端登录
				console.log('登录');
				http.post('/api-mini/user/login', { openid: this.openid }).then(res => {
					console.log(res)
					const response = res
					if(response.code === 200) {
						const data = response.data
						const userInfo = {
							openid: this.openid,
							name: data.name,
							role: data.role,
							phone: data.role === 'teacher' ? data.phone : data.parent_phone
						}
						this.userStore.setUserInfo(userInfo)
					} else {
						uni.navigateTo({url: '/pages/wechat/bind?openid=' + this.openid})
					}
				}).catch(res => { console.log(res) })
			}
		}
	}
</script>
